package com.mtnz.njk.Service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.mtnz.njk.GexinUtil.PushToSingle;
import com.mtnz.njk.Mapper.*;
import com.mtnz.njk.Util.CommentAsk;
import com.mtnz.njk.Util.ReplyCommentAsk;
import com.mtnz.njk.Util.ReplyCommentAskReply;
import com.mtnz.njk.entity.*;
import com.mtnz.njk.model.CommentAskModel;
import com.mtnz.njk.result.PageInfo;
import com.mtnz.njk.result.ResponseMessage;
import com.mtnz.njk.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommentAskService {

    @Autowired
    CommunityUserMapper communityUserMapper;

    @Autowired
    CommunityUserInfoMapper communityUserInfoMapper;

    @Autowired
    CommentAskMapper commentAskMapper;//提问评论

    @Autowired
    CommentAskImgMapper commentAskImgMapper;//提问评论图

    @Autowired
    PraiseAskCommentMapper praiseAskCommentMapper;//评论点赞

    @Autowired
    CollectionAskMapper collectionAskMapper;

    @Autowired
    UserTaskMapperr userTaskMapperr;

    @Autowired
    CountCommunityMapper countCommunityMapper;

    @Autowired
    UserTaskCountMapper userTaskCountMapper;

    @Autowired
    AskMapper askMapper;

    @Autowired
    NewsMapper newsMapper;

    /**
     * 评论提问
     */
    @Transactional
    public ResponseResult CommentAsk(String userId, String askId, String message, String img) throws Exception {
        //保存评论
        CommentAskEntity commentAskEntity = new CommentAskEntity();
        String commentAskId = IdUtil.simpleUUID();
        commentAskEntity.setCommentAskId(commentAskId);
        commentAskEntity.setMessage(message);
        commentAskEntity.setName("");
        commentAskEntity.setReplyId("");
        commentAskEntity.setAskId(askId);
        commentAskEntity.setUserId(userId);
        commentAskEntity.setReplyName("");
        commentAskEntity.setCreateDate(DateUtil.now());
        commentAskEntity.setStatus("0");
        commentAskEntity.setViews("0");
        commentAskEntity.setMonth(DateUtil.today());
        commentAskEntity.setPid("");
        commentAskMapper.insert(commentAskEntity);
        // 修改关注这问题的状态
        collectionAskMapper.updateStatus(askId);
        new Thread(new CommentAsk(askId, message, userId, askMapper, communityUserMapper, newsMapper,
                "http://www.meitiannongzi.com/nongjike/static/jsp/share_tiwen.html?TIWEN_ID=" + askId)).start();
        //推送消息
        AskEntity askEntity = askMapper.selectByPrimaryKey(askId);
        NjkUserEntity njkUserEntitys = communityUserMapper.selectByPrimaryKey(askEntity.getUserId());
        PushToSingle pushToSingle = new PushToSingle();
        if (njkUserEntitys.getClientId() != null && !"".equals(njkUserEntitys.getClientId())) {
            pushToSingle.pushToSingle(njkUserEntitys.getClientId(), "", "", 2, "xxxx", 2);
        }
        //给关注这个提问的人推送消息
        Example example = new Example(CollectionAskEntity.class);
        example.createCriteria().andEqualTo("askId", askId);
        List<CollectionAskEntity> collectionAskEntities = collectionAskMapper.selectByExample(example);
        if (collectionAskEntities != null) {
            for (CollectionAskEntity entity : collectionAskEntities) {
                String userId1 = entity.getUserId();
                Example example1 = new Example(NjkUserEntity.class);
                example1.createCriteria().andEqualTo("userId", userId1);
                List<NjkUserEntity> njkUserEntities = communityUserMapper.selectByExample(example1);
                for (NjkUserEntity njkUserEntity : njkUserEntities) {
                    if (njkUserEntity.getClientId() != null && !"".equals(njkUserEntity.getClientId())) {
                        pushToSingle.pushToSingle(njkUserEntity.getClientId(), "", "", 2, "gz", 2);
                    }
                }
            }
        }
        String inform = "";
        if (message != null && !("").equals(message) && message.length() > 3) {
            Example example2 = new Example(UserTaskEntity.class);
            example2.createCriteria().andEqualTo("userId", userId);
            List<UserTaskEntity> userTaskEntities = userTaskMapperr.selectByExample(example2);
            if (userTaskEntities != null && userTaskEntities.size() > 0) {
                for (UserTaskEntity userTaskEntity : userTaskEntities) {
                    Integer.parseInt(userTaskEntity.getQuizStatus().toString());
                    Integer quizNum = Integer.parseInt(userTaskEntity.getQuizNum().toString()) + 1;
                    CountCommunityEntity countCommunityEntity = new CountCommunityEntity();
                    //判断今天是否已完成 任务
                    if (quizNum <= 8) {
                        //添加到社区类型
                        countCommunityEntity.setCommunityType(1);
                        countCommunityEntity.setCreateTime(DateUtil.date());
                        countCommunityEntity.setUserId(userId);
                        countCommunityEntity.setNum("1");
                        countCommunityEntity.setCommunityId(askId);
                        countCommunityEntity.setOrderNum("");
                        countCommunityEntity.setAudit(0);
                        countCommunityEntity.setNews("回复提问");
                        countCommunityMapper.insert(countCommunityEntity);
                        //增加用户积分
                        NjkUserEntity njkUserEntity = communityUserMapper.selectByPrimaryKey(userId);
                        njkUserEntity.setIntegral(njkUserEntity.getIntegral() + 1);
                        //增加总积分
                        njkUserEntity.setTotalIntegral(njkUserEntity.getTotalIntegral() + 1);
                        communityUserMapper.updateByPrimaryKey(njkUserEntity);
                        //添加用户任务
                        userTaskEntity.setUserId(userId);
                        userTaskEntity.setQuizNum(quizNum);
                        userTaskEntity.setQuizStatus(1);
                        userTaskMapperr.updateByPrimaryKey(userTaskEntity);
                        //添加单个任务
                        UserTaskCountEntity userTaskCountEntity = new UserTaskCountEntity();
                        userTaskCountEntity.setUserId(userId);
                        userTaskCountEntity.setTaskType(3);
                        userTaskCountEntity.setCreateTime(DateUtil.date());
                        userTaskCountMapper.insert(userTaskCountEntity);
                        inform = "1";
                    }
                }
            }
        }
        //保存图片
        CommentAskImgEntity commentAskImgEntity = new CommentAskImgEntity();
        if (img != null && !("").equals(img) && img != "") {
            String[] split = img.split(",");
            List<String> strings = Arrays.asList(split);
            for (String string : strings) {
                commentAskImgEntity.setCommentAskId(commentAskId);
                commentAskImgEntity.setImg(string);
                commentAskImgEntity.setCreateDate(DateUtil.now());
                commentAskImgMapper.insert(commentAskImgEntity);
            }
        }
        return new ResponseResult(ResponseMessage.OK, inform);
    }

    /**
     * 回复提问评论
     */
    @Transactional
    public ResponseResult replyCommentAsk(String userId, String askId, String message, String commentAskId) throws Exception {
        CommentAskEntity commentAskEntity = new CommentAskEntity();
      /*  //获取用户数据
        Example example = new Example(NjkUserEntity.class);
        example.createCriteria().andEqualTo("userId", userId);
        List<NjkUserEntity> njkUserEntities = communityUserMapper.selectByExample(example);
        //获取回复表数据
        CommentAskEntity commentAskEntitys = commentAskMapper.selectByPrimaryKey(commentAskId)*/
        ;

        //保存回复
        commentAskEntity.setCommentAskId(IdUtil.simpleUUID());
        commentAskEntity.setUserId(userId);
        commentAskEntity.setAskId(askId);
        commentAskEntity.setMessage(message);
        commentAskEntity.setName("");
        commentAskEntity.setReplyId("");
        commentAskEntity.setReplyName("");
        commentAskEntity.setCreateDate(DateUtil.now());
        commentAskEntity.setStatus("1");
        commentAskEntity.setViews("0");
        commentAskEntity.setMonth(DateUtil.today());
        commentAskEntity.setPid(commentAskId);
        commentAskMapper.insert(commentAskEntity);
        new Thread(new ReplyCommentAsk(userId, askId, message, commentAskId, commentAskMapper,
                communityUserMapper, newsMapper, "http://www.meitiannongzi.com/nongjike/static/jsp/share_tiwen.html?TIWEN_ID=" + askId))
                .start();
        //推送
        AskEntity askEntity = askMapper.selectByPrimaryKey(askId);
        NjkUserEntity njkUserEntitys = communityUserMapper.selectByPrimaryKey(askEntity.getUserId());
        PushToSingle pushToSingle = new PushToSingle();
        if (njkUserEntitys.getClientId() != null && !"".equals(njkUserEntitys.getClientId())) {
            pushToSingle.pushToSingle(njkUserEntitys.getClientId(), "", "", 2, "xxxx", 2);
        }
        //给关注这个提问的人推送消息
        Example example = new Example(CollectionAskEntity.class);
        example.createCriteria().andEqualTo("askId", askId);
        List<CollectionAskEntity> collectionAskEntities = collectionAskMapper.selectByExample(example);
        if (collectionAskEntities != null) {
            for (CollectionAskEntity entity : collectionAskEntities) {
                String userId1 = entity.getUserId();
                Example example1 = new Example(NjkUserEntity.class);
                example1.createCriteria().andEqualTo("userId", userId1);
                List<NjkUserEntity> njkUserEntities = communityUserMapper.selectByExample(example1);
                for (NjkUserEntity njkUserEntity : njkUserEntities) {
                    if (njkUserEntity.getClientId() != null && !"".equals(njkUserEntity.getClientId())) {
                        pushToSingle.pushToSingle(njkUserEntity.getClientId(), "", "", 2, "gz", 2);
                    }
                }
            }
        }
        //增加用户积分
        String inform = "";
        Example example2 = new Example(UserTaskEntity.class);
        example2.createCriteria().andEqualTo("userId", userId);
        List<UserTaskEntity> userTaskEntities = userTaskMapperr.selectByExample(example2);
        if (message != null && message.length() > 3) {
            if (userTaskEntities.size() > 0 && userTaskEntities != null) {
                for (UserTaskEntity userTaskEntity : userTaskEntities) {
                    Integer.parseInt(userTaskEntity.getQuizStatus().toString());
                    Integer quizNum = Integer.parseInt(userTaskEntity.getQuizNum().toString()) + 1;
                    CountCommunityEntity countCommunityEntity = new CountCommunityEntity();
                    //判断今天是否已完成 任务
                    if (quizNum <= 8) {
                        //添加到社区类型
                        countCommunityEntity.setCommunityType(1);
                        countCommunityEntity.setCreateTime(DateUtil.date());
                        countCommunityEntity.setUserId(userId);
                        countCommunityEntity.setNum("1");
                        countCommunityEntity.setCommunityId(askId);
                        countCommunityEntity.setOrderNum("");
                        countCommunityEntity.setAudit(0);
                        countCommunityEntity.setNews("回复评论");
                        countCommunityMapper.insert(countCommunityEntity);
                        //增加用户积分
                        NjkUserEntity njkUserEntity = communityUserMapper.selectByPrimaryKey(userId);
                        njkUserEntity.setIntegral(njkUserEntity.getIntegral() + 1);
                        //增加总积分
                        njkUserEntity.setTotalIntegral(njkUserEntity.getTotalIntegral() + 1);
                        communityUserMapper.updateByPrimaryKey(njkUserEntity);
                        //添加用户任务
                        userTaskEntity.setUserId(userId);
                        userTaskEntity.setQuizNum(quizNum);
                        userTaskEntity.setQuizStatus(1);
                        userTaskMapperr.updateByPrimaryKey(userTaskEntity);
                        //添加单个任务
                        UserTaskCountEntity userTaskCountEntity = new UserTaskCountEntity();
                        userTaskCountEntity.setUserId(userId);
                        userTaskCountEntity.setTaskType(3);
                        userTaskCountEntity.setCreateTime(DateUtil.date());
                        userTaskCountMapper.insert(userTaskCountEntity);
                        inform = "1";
                    }
                }
            }
        }

        return new ResponseResult(ResponseMessage.OK, inform);
    }

    /**
     * 回复提问评论回复
     */
    @Transactional
    public ResponseResult replyCommentAsks(String userId, String askId, String message, String replyId, String pid) throws Exception {

        //保存回复
        CommentAskEntity commentAskEntity = new CommentAskEntity();
        commentAskEntity.setCommentAskId(IdUtil.simpleUUID());
        commentAskEntity.setUserId(userId);
        commentAskEntity.setAskId(askId);
        commentAskEntity.setMessage(message);
        commentAskEntity.setName("");
        commentAskEntity.setReplyId(replyId);
        commentAskEntity.setReplyName("");
        commentAskEntity.setCreateDate(DateUtil.now());
        commentAskEntity.setStatus("1");
        commentAskEntity.setViews("0");
        commentAskEntity.setMonth(DateUtil.today());
        commentAskEntity.setPid(pid);
        commentAskMapper.insert(commentAskEntity);

        new Thread(new ReplyCommentAskReply(userId, askId, message, replyId, askMapper, communityUserMapper,
                newsMapper, "http://www.meitiannongzi.com/nongjike/static/jsp/share_tiwen.html?TIWEN_ID=" + askId)).start();
        //推送
        AskEntity askEntity = askMapper.selectByPrimaryKey(askId);
        NjkUserEntity njkUserEntitys = communityUserMapper.selectByPrimaryKey(askEntity.getUserId());
        PushToSingle pushToSingle = new PushToSingle();
        if (njkUserEntitys.getClientId() != null && !"".equals(njkUserEntitys.getClientId())) {
            pushToSingle.pushToSingle(njkUserEntitys.getClientId(), "", "", 2, "xxxx", 2);
        }
        //给关注这个提问的人推送消息
        Example example = new Example(CollectionAskEntity.class);
        example.createCriteria().andEqualTo("askId", askId);
        List<CollectionAskEntity> collectionAskEntities = collectionAskMapper.selectByExample(example);
        if (collectionAskEntities != null) {
            for (CollectionAskEntity entity : collectionAskEntities) {
                String userId1 = entity.getUserId();
                Example example1 = new Example(NjkUserEntity.class);
                example1.createCriteria().andEqualTo("userId", userId1);
                List<NjkUserEntity> njkUserEntities = communityUserMapper.selectByExample(example1);
                for (NjkUserEntity njkUserEntity : njkUserEntities) {
                    if (njkUserEntity.getClientId() != null && !"".equals(njkUserEntity.getClientId())) {
                        pushToSingle.pushToSingle(njkUserEntity.getClientId(), "", "", 2, "gz", 2);
                    }
                }
            }
        }
        //增加用户积分
        String inform = "";
        Example example2 = new Example(UserTaskEntity.class);
        example2.createCriteria().andEqualTo("userId", userId);
        List<UserTaskEntity> userTaskEntities = userTaskMapperr.selectByExample(example2);
        if (message != null && message.length() > 3) {
            if (userTaskEntities.size() > 0 && userTaskEntities != null) {
                for (UserTaskEntity userTaskEntity : userTaskEntities) {
                    Integer.parseInt(userTaskEntity.getQuizStatus().toString());
                    Integer quizNum = Integer.parseInt(userTaskEntity.getQuizNum().toString()) + 1;
                    CountCommunityEntity countCommunityEntity = new CountCommunityEntity();
                    //判断今天是否已完成 任务
                    if (quizNum <= 8) {
                        //添加到社区类型
                        countCommunityEntity.setCommunityType(1);
                        countCommunityEntity.setCreateTime(DateUtil.date());
                        countCommunityEntity.setUserId(userId);
                        countCommunityEntity.setNum("1");
                        countCommunityEntity.setCommunityId(askId);
                        countCommunityEntity.setOrderNum("");
                        countCommunityEntity.setAudit(0);
                        countCommunityEntity.setNews("回复提问评论");
                        countCommunityMapper.insert(countCommunityEntity);
                        //增加用户积分
                        NjkUserEntity njkUserEntity = communityUserMapper.selectByPrimaryKey(userId);
                        njkUserEntity.setIntegral(njkUserEntity.getIntegral() + 1);
                        //增加总积分
                        njkUserEntity.setTotalIntegral(njkUserEntity.getTotalIntegral() + 1);
                        communityUserMapper.updateByPrimaryKey(njkUserEntity);
                        //添加用户任务
                        userTaskEntity.setUserId(userId);
                        userTaskEntity.setQuizNum(quizNum);
                        userTaskEntity.setQuizStatus(1);
                        userTaskMapperr.updateByPrimaryKey(userTaskEntity);
                        //添加单个任务
                        UserTaskCountEntity userTaskCountEntity = new UserTaskCountEntity();
                        userTaskCountEntity.setUserId(userId);
                        userTaskCountEntity.setTaskType(3);
                        userTaskCountEntity.setCreateTime(DateUtil.date());
                        userTaskCountMapper.insert(userTaskCountEntity);
                        inform = "1";
                    }
                }
            }
        }
        return new ResponseResult(ResponseMessage.OK, inform);
    }

    /**
     * 问答详情回答列表
     */
    public ResponseResult findCommentList(String askId, String userId, Integer pageNum, Integer pageSize) {
        //分页
        PageHelper.startPage(pageNum, pageSize);
        //获取帖子评论信息
        List<CommentAskModel> listReply = commentAskMapper.findListReply("0", askId);
        for (CommentAskModel commentAskModel : listReply) {
            //查询点赞记录
            if (praiseAskCommentMapper.showPraiseCommentStatus(commentAskModel.getCommentAskId(), userId) != null) {
                commentAskModel.setZan("1");
            } else {
                commentAskModel.setZan("0");
            }
            //获取评论图
            List<CommentAskImgEntity> commentAskImgEntities = commentAskImgMapper.showCommentAskImg(commentAskModel.getCommentAskId());
            commentAskModel.setCommentAskImg(commentAskImgEntities);

            //获取回复
            Example example = new Example(CommentAskEntity.class);
            example.setOrderByClause("create_date ASC");
            example.createCriteria().andEqualTo("status", 1).andEqualTo("pid", commentAskModel.getCommentAskId());
            List<CommentAskEntity> commentAskEntities = commentAskMapper.selectByExample(example);
            commentAskModel.setComment(commentAskEntities);
            for (CommentAskEntity commentAskEntity : commentAskEntities) {
                //获取评论人姓名
                Example example1 = new Example(NjkUserEntity.class);
                example1.createCriteria().andEqualTo("userId", commentAskEntity.getUserId());
                List<NjkUserEntity> njkUserEntities = communityUserMapper.selectByExample(example1);
                for (NjkUserEntity njkUserEntity : njkUserEntities) {
                    String name = njkUserEntity.getNickName();
                    commentAskEntity.setName(name);
                }

                //获取回复人姓名
                Example example2 = new Example(NjkUserEntity.class);
                example2.createCriteria().andEqualTo("userId", commentAskEntity.getReplyId());
                List<NjkUserEntity> njkUserEntities1 = communityUserMapper.selectByExample(example2);
                for (NjkUserEntity njkUserEntity : njkUserEntities1) {
                    String name = njkUserEntity.getNickName();
                    commentAskEntity.setReplyName(name);
                }

                //获取用户头像
                Example example3 = new Example(NjkUserInfoEntity.class);
                example3.createCriteria().andEqualTo("userId", commentAskEntity.getUserId());
                List<NjkUserInfoEntity> njkUserInfoEntities = communityUserInfoMapper.selectByExample(example3);
                for (NjkUserInfoEntity njkUserInfoEntity : njkUserInfoEntities) {
                    String img = njkUserInfoEntity.getImg();
                    commentAskEntity.setImg(img);
                }
            }
        }
        PageInfo pageInfo = new PageInfo<>(listReply);
        return new ResponseResult(ResponseMessage.OK, pageInfo);
    }

    /**
     * 提问评论点赞
     */
    @Transactional
    public ResponseResult askCommentPraise(String commentAskId, String userId) throws Exception {

        CommentAskEntity commentAskEntity = commentAskMapper.selectByPrimaryKey(commentAskId);
        //封装结果集
        Map map = new HashMap<>();

        //查询是否有该用户对该文章的点赞记录
        Example example = new Example(PraiseAskCommentEntity.class);
        example.createCriteria().andEqualTo("commentAskId", commentAskId)
                .andEqualTo("userId", userId);
        List<PraiseAskCommentEntity> praiseAskCommentEntities = praiseAskCommentMapper.selectByExample(example);
        String status = "";
        if (praiseAskCommentEntities != null && praiseAskCommentEntities.size() > 0) {

            //如果找到了这条记录，则删除该记录，同时文章的点赞数减1
            PraiseAskCommentEntity praiseAskCommentEntity = praiseAskCommentEntities.get(0);
            praiseAskCommentEntity.getCommentAskId();
            praiseAskCommentEntity.getUserId();

            //删除记录
            praiseAskCommentMapper.deletePraiseAsk(praiseAskCommentEntity);

            //文章点赞数减1，查询时使用Mysql行级锁解决并发覆盖问题
            if (Integer.parseInt(commentAskEntity.getViews()) > 0) {
                Integer i = Integer.parseInt(commentAskEntity.getViews()) - 1;
                commentAskEntity.setViews(String.valueOf(i));
                commentAskMapper.updateByPrimaryKey(commentAskEntity);
            }
            status = "0";
        } else {
            PraiseAskCommentEntity praiseAskCommentEntity = new PraiseAskCommentEntity();
            //如果没有找到这条记录，则添加这条记录，同时文章点赞数加1
            praiseAskCommentEntity.setCommentAskId(commentAskId);
            praiseAskCommentEntity.setUserId(userId);
            //添加记录
            praiseAskCommentMapper.insert(praiseAskCommentEntity);
            //文章点赞数加1，查询时使用Mysql行级锁解决并发覆盖问题
            Integer i = Integer.parseInt(commentAskEntity.getViews()) + 1;
            commentAskEntity.setViews(String.valueOf(i));
            commentAskEntity.setViews(String.valueOf(i));
            commentAskMapper.updateByPrimaryKey(commentAskEntity);
            status = "1";
        }
        map.put("status", status);
        map.put("views", commentAskEntity.getViews());
        return new ResponseResult(ResponseMessage.OK, map);

    }
}
